package com.sds.replicator.servlets;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;

@Singleton
public class DynamicReplicator extends FetcherServlet {

    boolean isTargetSet = false;
    public static String LOCAL_PATH = "/get";

    @Inject
    public DynamicReplicator() {
        super(LOCAL_PATH, "http://localhost:8081/");
    }

    @Override
    protected void service(HttpServletRequest incomingRequest, HttpServletResponse response) throws ServletException, IOException {
        String targetUrl = incomingRequest.getParameter("url");
        if (!targetUrl.startsWith("/")) {
            URL tempURL = new URL(targetUrl);
            targetHost = String.format("%s://%s:%s/", tempURL.getProtocol(), tempURL.getHost(), tempURL.getPort());
            logger.info("Dynamic set target host to:" + targetHost);
            isTargetSet = true;
        }
        super.service(incomingRequest, response);
    }
}
